

// Amis内置的调试器需要这里的css
import 'amis/lib/helper.css';
import '@fortawesome/fontawesome-free/css/all.css';
import '@fortawesome/fontawesome-free/css/v4-shims.css';
import 'amis/lib/themes/cxd.css';

//import 'amis/sdk/iconfont.css';
import 'amis-ui/lib/locale/en-US';
import 'amis-ui/lib/locale/zh-CN';
import '@nop-chaos/sdk/lib/style.css'




import type { App } from 'vue';
import {ref} from 'vue'

import { clearLocalCache, registerAdapter, XuiPage } from '@nop-chaos/sdk';

import IconSelect from '../components/IconSelect/index.vue'
import  router  from '../router'
import store  from '../store'
import useUserStore  from '/@/store/modules/user'
import { getToken,removeToken,setToken } from '/@/utils/auth';

const currentLocale = ref("zh-CN")
const i18n = {
    t(msg:string){
        return msg
    }
}

function initAdapter(app: App) {
    registerAdapter({
        /**
         * 返回当前的locale
         */
        useLocale(): string {
            return currentLocale.value
        },

        useI18n() {
            return {
                t: i18n.t
            }
        },

        /**
         * 返回当前的全局store
         */
        useStore() {
            return store
        },

        useRouter() {
            return router
        },

        useSettings() {
            return {
                apiUrl: ''
            }
        },

        /**
         * 返回当前的认证token
         */
        useAuthToken(): string {
            return getToken()
        },

        setAuthToken(token?: string) {
            if(!token){
                removeToken()
            }else{
                setToken(token)
            }
        },

        isUserInRole(role: string): boolean {
            return true
        },       

        useTenantId(): string {
            return ""
        },

        useAppId(): string {
            return "nop-chaos"
        },

        /**
         * 自动退出时执行的回调
         */
        logout(): void {
            router.push("/login")
        },

        /**
         * 根据组件名加载Vue组件
         */
        resolveVueComponent(name: string): any {
            return app.component(name)
        }
    })
}
export function initNopApp(app:App){
   initAdapter(app)
   app.component("amis-page", XuiPage)
   app.component("icon-picker",IconSelect)
   //app.component("icon",Icon)
   useUserStore().$subscribe((mutation)=>{
      // 登录信息变化的时候清空页面缓存和字典缓存
      if(mutation.events && mutation.events){
         if(Array.isArray(mutation.events)){
            for(const event of mutation.events){
               if(event.key == 'userInfo'){
                  clearLocalCache()
               }
            }
         }else if(mutation.events.key == 'userInfo'){
            clearLocalCache()
         }
      }
   })
}